package util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.StringReader;
import java.net.URLEncoder;

import javax.json.Json;
import javax.json.JsonObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import beans.Cliente;
import requisicao.Requisicao;

public class Util {
	
	public static boolean validarServico(Requisicao requisicao){
		String arquivoBase = "conf.properties";		
		Path path  = Paths.get(arquivoBase);
		String caminho = path.toAbsolutePath().toString().substring(0,path.toAbsolutePath().toString().length()-arquivoBase.length())+"src\\servicos\\ ";	
		caminho = caminho.replace("\\", "\\\\");			
		File dir = new File(caminho);
		File[] files = dir.listFiles();
		for (File file2 : files) {
			if(file2.getName().toString().equals(requisicao.getCabecalho().getRecurso().toString().substring(1)+".java")){
				return true;
			}
		}	
		return false;
	}
	public static String getServico(Requisicao requisicao){		
		return requisicao.getCabecalho().getRecurso().toString().substring(1)+".java";	
	}
	public static String lerLinha(InputStream in) throws IOException{
		StringBuilder sb = new StringBuilder();
		
		int b = 0;
		do {
			try {
				b = in.read();
				
				if (b == -1) throw new IOException("Invalid input data");
				
				if (b != '\r' && b != '\n') {
					sb.append((char) b);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
					
		} while (b != '\n');
		return sb.toString();
	}
	
	public static String lerString(InputStream in, int length) throws IOException {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < length; i++) {
			int b = in.read();	
			if (b == -1) throw new IOException("Invalid input data");
			sb.append((char) b);
		}
		byte bytes[] = sb.toString().getBytes();
		
		
		return new String(bytes, "UTF-8");
	}
	
	public static String[] getLocation(Cliente cliente) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String[] location = new String[2];
		try {		
			HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?address=" + URLEncoder.encode(cliente.getEnderecoCompleto(), "UTF-8"));
			
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity) : null;
					} else {
						throw new ClientProtocolException("Unexpected response status: " + status);
					}
				}
			};	
			
			String responseBody = httpClient.execute(httpGet, responseHandler);
		
			JsonObject obj = Json.createReader(new StringReader(responseBody)).readObject();
			
			System.out.println("// LOCATION ***************************");
			System.out.println(obj.toString());
			
			String status = obj.getString("status");
			
			if ("OVER_QUERY_LIMIT".equals(status)) {
				System.out.println("OVER_QUERY_LIMIT");
				return null;
			} else {
				JsonObject res = obj.getJsonArray("results").getJsonObject(0);
				
				location = new String[2];
				
				location[0] = res.getJsonObject("geometry").getJsonObject("location").get("lat").toString();
				location[1] = res.getJsonObject("geometry").getJsonObject("location").get("lng").toString();
				
				return location;
			}
		} catch(Exception e) {
//			e.printStackTrace();
			
			location[0] = "0";
			location[1] = "0";
			
			return location;
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
